package com.zipou.framework.gwt.client.widget;

import java.util.Date;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.datepicker.client.DatePicker;

public class MyDateField extends TextBox{

        
        private String format;
        private boolean isEmpty;
        
        
        public MyDateField() {
                super();
                
                isEmpty=true;   
                this.setStyleName("inputEmpty");
                this.format = "dd/MM/yyyy";
                
                final PopupPanel popupPanel = new PopupPanel(true);
                
                final DatePicker datePicker = new DatePicker();
                datePicker.addValueChangeHandler(new ValueChangeHandler() {
                        public void onValueChange(ValueChangeEvent event) {
                                Date date = (Date) event.getValue();
                                String dateString = DateTimeFormat.getFormat(getFormat()).format(date);
                                This().setText(dateString);
                                isEmpty = false;
                                popupPanel.hide();
                        }

                });
                
                popupPanel.add(datePicker);

                this.setReadOnly(true);
                
                
                this.addClickHandler(new ClickHandler() {
                        public void onClick(ClickEvent event) {
                                popupPanel.setPopupPosition(This().getAbsoluteLeft(), This().getAbsoluteTop() + This().getOffsetHeight());
                                popupPanel.show();
                        }
                });     
        }
        
        final public void setFormat(String format) {
                this.format = format;
        }
        
        final public String getFormat() {
                return this.format;
        }
        
        final public boolean isEmpty() {
                return this.isEmpty;
        }
        
       private TextBox This() {
                return this;
        }
        
        final public Date getDate() {
            if (this.isEmpty) {
            	return null;
            }
        	return DateTimeFormat.getFormat(getFormat()).parse(this.getText());
        }
}